<template>
    <div class="box">
        <div class="top">
            <div class="back" @click="$router.back()">
                <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M25 5L10 20L25 35" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="font_title">
                <svgIcon iconName="icon-sousuox" font-size="40px"></svgIcon>
                <input 
                    type="text" 
                    v-model="searchQuery" 
                    placeholder="请输入类别名称、金额或时间！"
                    @input="handleSearch"
                >
            </div>
        </div>
        <div class="content">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-overlay">
                <div class="loading-spinner"></div>
            </div>
            
            <!-- 错误提示 -->
            <div v-if="error" class="error-message">
                {{ error }}
                <button @click="fetchBills" class="retry-btn">重试</button>
            </div>

            <!-- 无数据提示 -->
            <div v-else-if="showNoData && searchQuery" class="no-data">
                <img src="../assets/tb/zanwu.png" alt="暂无数据">
                <p>{{ error || '暂无账单记录' }}</p>
            </div>
            
            <!-- 账单列表 -->
            <div v-else-if="searchQuery" v-for="(group, date) in filteredGroupedBills" :key="date" class="item">
                <div class="item_time">
                    <div>{{ formatDate(date) }}</div>
                    <div>
                        支出：{{ group.expense.toFixed(2) }}
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        收入：{{ group.income.toFixed(2) }}
                    </div>
                </div>
                <div v-for="bill in group.bills" :key="`${bill.id}_${bill._id}`" class="item_cont" @click="goToContent(bill)">
                    <div>
                        <svgIcon :iconName="bill.icon" font-size="50px"></svgIcon>
                        <span>{{ bill.category }}</span>
                    </div>
                    <div class="cont_num" :class="{ 'expense': bill.type === 'expense', 'income': bill.type === 'income' }">
                        {{ bill.type === 'expense' ? '-' : '+' }}{{ bill.amount.toFixed(2) }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import request from '../utils/request';

const router = useRouter();
const bills = ref([]);
const loading = ref(false);
const error = ref('');
const searchQuery = ref('');

// 获取账单数据
const fetchBills = async () => {
    loading.value = true;
    error.value = '';
    
    try {
        const response = await request.get('/api/category/categories', null, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (Array.isArray(response.data)) {
            bills.value = response.data.flatMap(item => {
                if (!Array.isArray(item.data)) {
                    console.warn('item.data 不是数组:', item);
                    return [];
                }
                
                return item.data.map(dataItem => {
                    return {
                        id: item.id,
                        _id: dataItem._id || Date.now() + Math.random(), // 确保 _id 存在
                        order: item.order,
                        time: dataItem.time || new Date().toISOString(),
                        type: item.type || 'expense',
                        amount: dataItem.value || 0,
                        category: item.name || '未分类',
                        icon: item.icon || 'icon-jiangjin'
                    };
                });
            });
        } else {
            console.error('数据格式不正确:', response.data);
            bills.value = [];
            error.value = '数据格式不正确';
        }
    } catch (err) {
        console.error('获取账单数据失败:', err);
        if (err.response && err.response.status === 401) {
            error.value = '登录已过期，请重新登录';
            localStorage.removeItem('userInfo');
        } else if (err.code === 'ECONNABORTED') {
            error.value = '请求超时，请检查网络连接';
        } else if (err.message.includes('Network Error')) {
            error.value = '网络连接失败，请检查网络设置';
        } else {
            error.value = '获取账单数据失败，请稍后重试';
        }
        bills.value = [];
    } finally {
        loading.value = false;
        // 如果有错误，显示错误提示
        if (error.value) {
            alert(error.value);
        }
    }
};

// 格式化日期字符串
const formatDateString = (dateStr) => {
    try {
        if (!dateStr) {
            return new Date().toISOString().split('T')[0];
        }
        
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
            return new Date().toISOString().split('T')[0];
        }
        return date.toISOString().split('T')[0];
    } catch (err) {
        console.error('日期格式化错误:', err);
        return new Date().toISOString().split('T')[0];
    }
};

// 按日期分组账单数据
const groupedBills = computed(() => {
    try {
        const groups = {};
        
        if (!Array.isArray(bills.value)) {
            console.error('bills 不是数组:', bills.value);
            return {};
        }
        
        bills.value.forEach(bill => {
            if (!bill) {
                console.warn('账单数据为空');
                return;
            }
            
            const date = formatDateString(bill.time);
            
            if (!groups[date]) {
                groups[date] = {
                    bills: [],
                    expense: 0,
                    income: 0
                };
            }
            
            const amount = parseFloat(bill.amount) || 0;
            const type = bill.type || 'expense';
            
            groups[date].bills.push({
                id: bill.id,
                _id: bill._id,
                order: bill.order,
                time: bill.time,
                type: type,
                amount: amount,
                category: bill.category || '未分类',
                icon: bill.icon || 'icon-jiangjin'
            });
            
            if (type === 'expense') {
                groups[date].expense += amount;
            } else {
                groups[date].income += amount;
            }
        });
        
        // 按日期降序排序
        return Object.fromEntries(
            Object.entries(groups).sort(([dateA], [dateB]) => dateB.localeCompare(dateA))
        );
    } catch (err) {
        console.error('账单分组处理错误:', err);
        return {};
    }
});

// 搜索过滤后的分组数据
const filteredGroupedBills = computed(() => {
    if (!searchQuery.value) {
        return groupedBills.value;
    }

    const query = searchQuery.value.toLowerCase();
    const filteredGroups = {};

    // 计算匹配度分数
    const calculateMatchScore = (bill) => {
        let score = 0;
        const category = bill.category.toLowerCase();
        // 将金额格式化为两位小数
        const amount = Number(bill.amount).toFixed(2);
        const date = formatDate(bill.time);

        // 类别名称完全匹配
        if (category === query) {
            score += 100;
        }
        // 类别名称包含查询词
        else if (category.includes(query)) {
            score += 50;
        }

        // 金额匹配逻辑
        if (amount === query) {
            // 完全匹配
            score += 100;
        } else if (amount.includes(query)) {
            // 检查是否包含小数点
            if (query.includes('.')) {
                // 如果查询词包含小数点,提高匹配分数
                score += 80;
            } else {
                // 普通包含匹配
                score += 50;
            }
        }

        // 日期完全匹配
        if (date === query) {
            score += 100;
        }
        // 日期包含查询词
        else if (date.includes(query)) {
            score += 50;
        }

        return score;
    };

    Object.entries(groupedBills.value).forEach(([date, group]) => {
        const filteredBills = group.bills.filter(bill => {
            // 将金额格式化为两位小数
            const amount = Number(bill.amount).toFixed(2);
            
            // 搜索类别名称
            if (bill.category.toLowerCase().includes(query)) {
                return true;
            }
            // 搜索金额
            if (amount.includes(query)) {
                return true;
            }
            // 搜索时间
            if (formatDate(bill.time).includes(query)) {
                return true;
            }
            return false;
        });

        if (filteredBills.length > 0) {
            // 对账单按匹配度排序
            filteredBills.sort((a, b) => {
                const scoreA = calculateMatchScore(a);
                const scoreB = calculateMatchScore(b);
                return scoreB - scoreA; // 降序排列
            });

            filteredGroups[date] = {
                bills: filteredBills,
                expense: filteredBills
                    .filter(bill => bill.type === 'expense')
                    .reduce((sum, bill) => sum + Number(bill.amount), 0),
                income: filteredBills
                    .filter(bill => bill.type === 'income')
                    .reduce((sum, bill) => sum + Number(bill.amount), 0)
            };
        }
    });

    // 对日期组进行排序
    const sortedGroups = Object.entries(filteredGroups)
        .sort(([dateA, groupA], [dateB, groupB]) => {
            // 首先按日期降序排序
            const dateCompare = dateB.localeCompare(dateA);
            if (dateCompare !== 0) {
                return dateCompare;
            }

            // 如果日期相同,比较组内最高匹配度
            const maxScoreA = Math.max(...groupA.bills.map(bill => calculateMatchScore(bill)));
            const maxScoreB = Math.max(...groupB.bills.map(bill => calculateMatchScore(bill)));
            return maxScoreB - maxScoreA;
        });

    return Object.fromEntries(sortedGroups);
});

// 格式化日期显示
const formatDate = (dateStr) => {
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
            return '无效日期';
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    } catch (err) {
        console.error('日期格式化错误:', err);
        return '无效日期';
    }
};

// 跳转到详情页
const goToContent = (bill) => {
    router.push({
        name: 'content',
        query: { 
            id: bill.id,
            _id: bill._id,
            type: bill.type,
            amount: bill.amount,
            category: bill.category,
            order: bill.order,
            icon: bill.icon,
            time: bill.time
        }
    });
};

// 处理搜索
const handleSearch = () => {
    // 搜索逻辑已通过计算属性实现
};

// 无数据提示的显示条件
const showNoData = computed(() => {
    return !loading.value && !error.value && Object.keys(filteredGroupedBills.value).length === 0;
});

// 组件挂载时获取数据
onMounted(() => {
    fetchBills();
});
</script>

<style lang="less" scoped>
.box {
    width: 100%;
    min-height: 100vh;
    overflow: hidden;
    .top {
        width: 100%;
        height: 150px;
        background-color: #fb8fae;
        color: #fff;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 100;
        display: flex;
        align-items: center;
        .back {
            width: 80px;
            height: 100%;
            text-align: center;
            line-height: 50px;
            svg {
                margin-top: 50px;
                width: 50px;
                height: 50px;
            }
        }
        .font_title {
            margin-left: 10px;
            width: 600px;
            background-color: #fff;
            border-radius: 30px;
            height: 80px;
            line-height: 80px;
            padding: 0 30px;
            display: flex;
            align-items: center;
            input {
                margin-left: 10px;
                width: 450px;
                height: 80px;
                font-size: 32px;
                color: #000;
            }
        }
    }
    .content {
        margin-top: 150px;
        width: 100%;
        background-color: #fff;
        padding-bottom: 120px;
        .item {
            width: 100%;
            .item_time {
                width: 100%;
                height: 50px;
                background-color: #f5f5f5;
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-size: 24px;
                padding: 0 20px;
                color: gray;
            }
            .item_cont {
                width: 100%;
                padding: 0 40px;
                display: flex;
                height: 90px;
                justify-content: space-between;
                align-items: center;
                font-size: 28px;
                div {
                    display: flex;
                    align-items: center;
                    span {
                        display: block;
                        margin-left: 20px;
                    }
                }
            }    
        }
    }
}

.cont_num {
    &.expense {
        color: #ff9bb7;
    }
    &.income {
        color: #80e57f;
    }
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.loading-spinner {
    width: 50px;
    height: 50px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #ff9bb7;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.error-message {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    z-index: 1000;
    
    .retry-btn {
        margin-top: 10px;
        padding: 8px 20px;
        background: #ff9bb7;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        
        &:hover {
            background: darken(#ff9bb7, 10%);
        }
    }
}

.no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    
    img {
        width: 120px;
        height: 120px;
        margin-bottom: 20px;
    }
    
    p {
        color: #999;
        font-size: 28px;
    }
}
</style>